package com.guli.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.eduservice.entity.EduChapter;
import com.guli.eduservice.entity.EduVideo;
import com.guli.eduservice.entity.chapter.ChapterVo;
import com.guli.eduservice.entity.chapter.VideoVo;
import com.guli.eduservice.mapper.EduChapterMapper;
import com.guli.eduservice.service.EduChapterService;
import com.guli.eduservice.service.EduVideoService;
import com.guli.servicebase.exceptionhandler.LingqiException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zql
 * @since 2021-11-27
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVideo(String courseId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("course_id", courseId);
        List<EduChapter> eduChapterList = baseMapper.selectList(queryWrapper);

        List<EduVideo> eduVideoList = eduVideoService.list(queryWrapper);

        List<ChapterVo> finalList = new ArrayList<>();

        for (int i = 0; i < eduChapterList.size(); i++) {
            EduChapter eduChapter = eduChapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);
            finalList.add(chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();
            for (int m = 0; m < eduVideoList.size(); m++) {
                EduVideo eduVideo = eduVideoList.get(m);
                if (eduVideo.getChapterId().equals(eduChapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }
        return finalList;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("chapter_id", chapterId);
        List<EduVideo> eduVideoList = eduVideoService.list(queryWrapper);
        if (!eduVideoList.isEmpty()) {
            throw new LingqiException(20001, "删除章节失败");
        }
        int delete = baseMapper.deleteById(chapterId);
        return delete > 0;
    }

    @Override
    public void removeChapterByCourseId(String courseId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("course_id", courseId);
        baseMapper.delete(queryWrapper);
    }
}
